package org.example.modules.user.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.common.utils.ThreadLocalUtil;
import org.example.modules.user.entry.ApplyDetails;
import org.example.modules.user.entry.vo.ApplyRecordsVo;
import org.example.modules.user.mapper.ApplyDetailsMapper;
import org.example.modules.user.service.ApplyDetailsService;
import org.example.modules.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * @Description ApplyDetailsServiceImpl
 * @Author xiaotian
 * @Date 2025-04-15
 */
@Service
public class ApplyDetailsServiceImpl extends ServiceImpl<ApplyDetailsMapper, ApplyDetails> implements ApplyDetailsService {

    @Autowired
    private ApplyDetailsMapper applyDetailsMapper;

    @Autowired
    private UserService userService;

    @Override
    public void addApplyDetails(JSONObject data) {
        ApplyDetails details = data.toJavaObject(ApplyDetails.class);
        details.setLegalNameIdAuth(data.getString("legalNameIdAuthImages"));
        details.setBusinessLicense(data.getString("businessLicenseImages"));
        details.setStatus("N");
        details.setUserName(ThreadLocalUtil.getUserId());
        details.setApplyTime(LocalDate.now().toString());
        details.setDealTime(LocalDate.now().toString());
        applyDetailsMapper.insert(details);
    }

    @Override
    public List<ApplyDetails> getApply() {
        return applyDetailsMapper.getAllApply();
    }

    @Transactional
    @Override
    public void updateApplyStatus(JSONObject data) {
        Integer Id = data.getInteger("id");
        String status = data.getString("status");
        String reason = "";
        if(data.getString("reason")!=null){
            reason=data.getString("reason");
        }
        ApplyDetails applyDetails = applyDetailsMapper.selectById(Id);

        if(status.equals("Y")){
            userService.updateAuthority(applyDetails.getUserName(),2);
        }
        applyDetailsMapper.updateApplyStatus(Id,status,reason);
    }

    @Override
    public List<ApplyRecordsVo> getApplyRecords(JSONObject data) {
        String userName = data.getString("userName");
        return applyDetailsMapper.getApplyRecords(userName);
    }

    @Override
    public ApplyDetails getApplyDetails(JSONObject data) {
        Integer id = data.getInteger("id");
        return applyDetailsMapper.getApplyDetails(id);
    }
}
